import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'

const routes = [
  {
    path: '/',
    component: () => import('@/views/Layout.vue'),
    children: [
      {
        path: '/',
        component: () => import('@/views/home')
      },
      {
        path: '/category/:id',
        component: () => import('@/views/category/index.vue')
      },
      {
        path: '/category/sub/:id',
        component: () => import('@/views/category/sub.vue')
      },
      {
        path: '/product/:id',
        component: () => import('@/views/goods/index.vue')
      },
      {
        path: '/cart',
        component: () => import('@/views/cart/index.vue')
      },
      {
        path: '/PayCheckout',
        component: () => import('@/views/member/pay/checkout.vue')
      },
      {
        path: '/member/pay',
        component: () => import('@/views/member/pay/index.vue')
      },
      {
        path: '/pay/callback',
        component: () => import('@/views/member/pay/components/result.vue')
      }
      ,
      {
        path: '/member',
        component: () => import('@/views/member/Layout'),
        children: [
          {
            path: '/member',
            component: () => import('@/views/member/home/index.vue'),
          },
          {
            // 个人中心 菜单激活 vue3.0 需要有嵌套关系才能模糊匹配 
            path: '/member/order',
            component: { render: () => h(<RouterView />) },
            children: [
              {
                path: '', component: () => import('@/views/member/order/index.vue')
              },
              {
                path: ':id', component: () => import('@/views/member/order/detail.vue')
              }
            ]
          },
          {
            path: '/member/coupons', component: () => import('@/views/member/coupons/index.vue')
          }
        ]
      }
    ]
  },
  {
    path: '/login',
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/login/callback',
    component: () => import('@/views/login/callback.vue')
  }
]

// 创建路由实例
const router = createRouter({
  // createWebHashHistory代表使用hash模式的路由
  history: createWebHashHistory(),
  routes,
  // 每次切换路由的时候滚动到顶部 
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})

// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})

export default router
